﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using ComicIsland.Common;
using ComicIsland.Common.Entities;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.StorageHelper;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.BackgroundTransfer;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views.CacheDownload
{
    public partial class ComicChapterCacheQueuePage : PhoneApplicationPage
    {
        private bool IsReloadData = false;
        private DownloadComic downloadComic = null;
        private bool IsInitialTransfer = false;

        public ComicChapterCacheQueuePage()
        {
            InitializeComponent();
            IsReloadData = true;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            IsReloadData = false;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            this.InitialTransferStatusCheck();
            //
            if (base.NavigationContext.QueryString.ContainsKey("DownloadComic"))
            {
                string paramDownloadComic = string.Empty;
                base.NavigationContext.QueryString.TryGetValue("DownloadComic", out paramDownloadComic);
                if (string.IsNullOrWhiteSpace(paramDownloadComic))
                {
                    base.NavigationService.GoBack();
                    return;
                }
                downloadComic = JSONHelper.Deserialize<DownloadComic>(paramDownloadComic);
                if (downloadComic == null)
                {
                    base.NavigationService.GoBack();
                    return;
                }
                if (IsReloadData)
                {
                    //新增或更新本地缓存（要下载漫画的缓存列中）
                    this.InsertOrUpdateLocalCache();
                    //添加至下载队列中去
                    //Task.Factory.StartNew(() => this.InsertOrUpdateDownloadChapterImageQueue());
                    this.InsertOrUpdateDownloadChapterImageQueue();
                    //InitialTransferStatusCheck();
                }
            }
            //加载下载过的漫画列表
            if (IsReloadData)
            {
                LoadDownloadQueueComicChapters();
            }
            //
            if (!IsInitialTransfer)
            {
                //页面重新加载时，刷新后台文件传输队列
                InitialTransferStatusCheck();
            }
            UpdateUI();
        }

        #region 下载队列
        void AddDownloadComicChapterImageToTransferQueue(ObservableCollection<DownloadComicChapterImage> downloadComicChapterImages, string filepath)
        {
            if (!(downloadComicChapterImages != null && downloadComicChapterImages.Count > 0))
                return;

            foreach (DownloadComicChapterImage dcci in downloadComicChapterImages)
            {
                if (BackgroundTransferService.Requests.Count() >= 25)
                {
                    break;
                }
                if (!(dcci.DownloadStatus == (int)DownloadComicChapterStatus.Pending || dcci.DownloadStatus == (int)DownloadComicChapterStatus.Downloading))
                    continue;

                Uri transferUri = new Uri(Uri.EscapeUriString(dcci.ImageUrl), UriKind.RelativeOrAbsolute);
                BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
                transferRequest.Method = "GET";
                Uri downloadUri = new Uri(string.Concat("shared/transfers/", KEYS.CacheImagePrefix, dcci.ComicId, "_", dcci.PartId, "_", MD5.GetMd5String(dcci.ImageUrl)), UriKind.RelativeOrAbsolute);
                transferRequest.DownloadLocation = downloadUri;
                LogHelper.LogInfo(downloadUri.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                //
                transferRequest.Tag = JSONHelper.Serialize<DownloadComicChapterImage>(dcci);
                transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
                try
                {
                    if (0 < BackgroundTransferService.Requests.Where(p => p.DownloadLocation == transferRequest.DownloadLocation).Count())
                    {
                        //已经存在了
                        continue;
                    }
                    BackgroundTransferService.Add(transferRequest);                    
                    dcci.DownloadStatus = (int)DownloadComicChapterStatus.Downloading;
                }
                catch (Exception err) { LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod()); }
            }            
            IsolatedStorageHelper.Instance.WriteText(JSONHelper.Serialize<ObservableCollection<DownloadComicChapterImage>>(downloadComicChapterImages), filepath, true);
            InitialTransferStatusCheck();
        }

        void InsertOrUpdateDownloadChapterImageQueue()
        {
            #region 获取要下载的漫画章节列表
            ObservableCollection<DownloadComic> localCacheItems = null;
            if (IsolatedStorageHelper.Instance.FileExists(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE))
            {
                string localCacheData = IsolatedStorageHelper.Instance.ReadText(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE);
                if (!string.IsNullOrWhiteSpace(localCacheData))
                {
                    localCacheItems = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(localCacheData);
                }
            }

            if (!(localCacheItems != null && localCacheItems.Count > 0))
            {
                return;
            }

            DownloadComicChapter dcc = null;
            foreach (DownloadComic item in localCacheItems)
            {
                //仍有未下载队列
                if (item.ComicId == downloadComic.ComicId && item.DownloadStatus == (int)DownloadComicChapterStatus.Pending)
                {
                    var ocChapters = item.Chapters;
                    if (!(ocChapters != null && ocChapters.Count > 0))
                    {
                        //无章节
                        continue;
                    }
                    //
                    foreach (var chapter in ocChapters)
                    {
                        if (chapter == null)
                            continue;
                        if (chapter.DownloadStatus == (int)DownloadComicChapterStatus.Pending)
                        {
                            ObservableCollection<DownloadComicChapterImage> localDownloadComicChapterImages = null;
                            string chapterImageQueueKey = string.Format(KEYS.CACHEDOWNLOAD_CHAPTER_IMAGE_QUEUE, chapter.ComicId, chapter.PartId);
                            if (IsolatedStorageHelper.Instance.FileExists(chapterImageQueueKey))
                            {
                                string localCacheData = IsolatedStorageHelper.Instance.ReadText(chapterImageQueueKey);
                                if (!string.IsNullOrWhiteSpace(localCacheData))
                                {
                                    localDownloadComicChapterImages = JSONHelper.Deserialize<ObservableCollection<DownloadComicChapterImage>>(localCacheData);
                                }
                            }
                            if (localDownloadComicChapterImages != null && localDownloadComicChapterImages.Count > 0)
                            {
                                var completedImagesTotal = localDownloadComicChapterImages.Where(p => p.DownloadStatus == (int)DownloadComicChapterStatus.Completed).Count();
                                if (localDownloadComicChapterImages.Count == completedImagesTotal)
                                {
                                    ////TODO 更新漫画章节下载状态，写入缓存
                                    chapter.DownloadStatus = (int)DownloadComicChapterStatus.Completed;
                                    UpdateLocalCacheFromDownloadComicChapter(chapter.ComicId, chapter.PartId, DownloadComicChapterStatus.Completed);
                                    continue;
                                }
                            }
                            //
                            dcc = chapter;
                            break;
                        }
                    }
                    //
                    //TODO 更新漫画下载状态，写入缓存
                    var completedTotal = item.Chapters.Where(p => p.DownloadStatus == (int)DownloadComicChapterStatus.Completed).Count();
                    if (ocChapters.Count == completedTotal)
                    {
                        item.DownloadStatus = (int)DownloadComicChapterStatus.Completed;
                        item.TotalCompleted++;
                        UpdateLocalCacheFromDownloadComic(item);
                        continue;
                    }
                }
            }
            if (dcc == null)
            {
                return;
            }
            #endregion 获取要下载的漫画章节列表
            //
            string key = string.Format(KEYS.CACHEDOWNLOAD_CHAPTER_IMAGE_QUEUE, this.downloadComic.ComicId, dcc.PartId);
            if (IsolatedStorageHelper.Instance.FileExists(key))
            {
                ObservableCollection<DownloadComicChapterImage> localDownloadComicChapterImages = null;
                string localCacheData = IsolatedStorageHelper.Instance.ReadText(key);
                if (!string.IsNullOrWhiteSpace(localCacheData))
                {
                    localDownloadComicChapterImages = JSONHelper.Deserialize<ObservableCollection<DownloadComicChapterImage>>(localCacheData);
                }
                IsInitialTransfer = true;
                this.AddDownloadComicChapterImageToTransferQueue(localDownloadComicChapterImages, key);
                return;
            }
            //获取漫画的章节中的图片地址，并缓存在本地
            #region 获取漫画章节中的图片地址列表
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, string.Format("/comic/comicsread_v3?bookid={0}&partid={1}&partVersion=3", this.downloadComic.ComicId, dcc.PartId));
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
            //
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //

                        var rootCharacterString = JSONHelper.Deserialize<JsonComicContent>(result);
                        if (!(rootCharacterString != null && !string.IsNullOrWhiteSpace(rootCharacterString.Info)))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var comicImages = new ObservableCollection<DownloadComicChapterImage>();
                            var itemsource = JSONHelper.Deserialize<ObservableCollection<JsonComicContentInfo>>(rootCharacterString.Info);
                            if (itemsource != null && itemsource.Count > 0)
                            {
                                foreach (JsonComicContentInfo jcci in itemsource)
                                {
                                    comicImages.Add(new DownloadComicChapterImage()
                                    {
                                        ComicId = this.downloadComic.ComicId,
                                        PartId = dcc.PartId,
                                        ImageUrl = jcci.Imgurl,
                                        Referer = jcci.Referer,
                                        DownloadStatus = (int)DownloadComicChapterStatus.Pending
                                    });
                                }
                            }
                            //漫画的章节中的图片地址列表
                            if (comicImages != null && comicImages.Count > 0)
                            {
                                //缓存
                                string text = JSONHelper.Serialize<ObservableCollection<DownloadComicChapterImage>>(comicImages);
                                IsolatedStorageHelper.Instance.WriteText(text, key);
                                LogHelper.LogInfo(key, this.GetType(), MethodBase.GetCurrentMethod());
                                //添加至后台下载队列
                                AddDownloadComicChapterImageToTransferQueue(comicImages, key);
                            }
                            else
                            {
                                //更新漫画的章节缓存中的下载状态  
                                foreach (DownloadComic dc in localCacheItems)
                                {
                                    if (dc == null)
                                        continue;
                                    if (dc.ComicId != this.downloadComic.ComicId)
                                        continue;
                                    foreach (DownloadComicChapter dcDcc in dc.Chapters)
                                    {
                                        if (dcDcc == null)
                                            continue;
                                        if (dcDcc.PartId == dcc.PartId)
                                        {
                                            dcDcc.DownloadStatus = (int)DownloadComicChapterStatus.ErrorEmptyImageList;
                                            break;
                                        }
                                    }
                                }
                                //
                                string text = JSONHelper.Serialize<ObservableCollection<DownloadComic>>(localCacheItems);
                                IsolatedStorageHelper.Instance.WriteText(text, KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE, true);
                            }
                        }
                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {

                }
            }, webTask);
            #endregion 获取漫画章节中的图片地址列表

        }
        #endregion 下载队列


        /// <summary>
        /// 新增或更新本地缓存
        /// </summary>
        void InsertOrUpdateLocalCache()
        {
            ObservableCollection<DownloadComic> localCacheItems = null;
            if (IsolatedStorageHelper.Instance.FileExists(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE))
            {
                string localCacheData = IsolatedStorageHelper.Instance.ReadText(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE);
                if (!string.IsNullOrWhiteSpace(localCacheData))
                {
                    localCacheItems = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(localCacheData);
                }
            }

            bool isUpdate = false;
            if (localCacheItems != null && localCacheItems.Count > 0)
            {
                foreach (DownloadComic item in localCacheItems)
                {
                    if (item.ComicId == downloadComic.ComicId)
                    {
                        //已经存在则需要一一比对
                        isUpdate = true;
                        item.DownloadStatus = (int)DownloadComicChapterStatus.Pending;//更新有未下载的标识
                        if (!(downloadComic != null && downloadComic.Chapters != null && downloadComic.Chapters.Count > 0))
                            return;
                        foreach (var currentItem in downloadComic.Chapters)
                        {
                            var isExist = (from p in item.Chapters where p.PartId == currentItem.PartId select p).FirstOrDefault<DownloadComicChapter>();
                            if (isExist == null)
                            {
                                if (!(item.Chapters != null && item.Chapters.Count > 0))
                                    item.Chapters = new ObservableCollection<DownloadComicChapter>();                                
                                item.Chapters.Add(currentItem);
                            }
                        }
                        break;
                    }
                }
                //如果是更新则需要一一比对来进行数据更新，如果是false则直接加入列表
                if (!isUpdate)
                {                   
                    localCacheItems.Add(downloadComic);
                }
                string jsonSerialize = JSONHelper.Serialize<ObservableCollection<DownloadComic>>(localCacheItems);
                IsolatedStorageHelper.Instance.WriteText(jsonSerialize, KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE, true);
            }
            else
            {
                string jsonSerialize = JSONHelper.Serialize<ObservableCollection<DownloadComic>>(new ObservableCollection<DownloadComic>() { downloadComic });
                IsolatedStorageHelper.Instance.WriteText(jsonSerialize, KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE, true);
            }
        }

        /// <summary>
        /// 加载当前漫画的章节下载队列
        /// </summary>
        void LoadDownloadQueueComicChapters()
        {
            if (!IsolatedStorageHelper.Instance.FileExists(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE))
                return;

            string localCacheData = IsolatedStorageHelper.Instance.ReadText(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE);
            if (string.IsNullOrWhiteSpace(localCacheData))
                return;
            var localCacheItems = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(localCacheData);
            if (!(localCacheItems != null && localCacheItems.Count > 0))
            {
                return;
            }
            var localCacheItem = localCacheItems.Where(p => p.ComicId == this.downloadComic.ComicId).FirstOrDefault<DownloadComic>();
            if (localCacheItem == null)
                return;
            //全部章节
            this.llsAll.ItemsSource = localCacheItem.Chapters;
            this.pivotAllChapter.Header = string.Format("全部({0})", this.llsAll.ItemsSource != null ? this.llsAll.ItemsSource.Count.ToString() : "0");
            //已完成的章节
            var itemsFinished = (from p in localCacheItem.Chapters where p.DownloadStatus == (int)DownloadComicChapterStatus.Completed select p).ToList<DownloadComicChapter>();
            if (itemsFinished != null && itemsFinished.Count > 0)
            {
                var ocItemsFinished = new ObservableCollection<DownloadComicChapter>(itemsFinished);
                this.llsFinished.ItemsSource = ocItemsFinished;
            }
            this.pivotFinishedChapter.Header = string.Format("已完成({0})", this.llsFinished.ItemsSource != null ? this.llsFinished.ItemsSource.Count.ToString() : "0");
            //下载中章节
            var itemsDownloading = (from p in localCacheItem.Chapters where p.DownloadStatus == (int)DownloadComicChapterStatus.Downloading select p).ToList<DownloadComicChapter>();
            if (itemsDownloading != null && itemsDownloading.Count > 0)
            {
                var ocItemsDownloadingd = new ObservableCollection<DownloadComicChapter>(itemsDownloading);
                this.llsAllDownloading.ItemsSource = ocItemsDownloadingd;
            }
            this.pivotDownloadingChapter.Header = string.Format("下载中({0})", this.llsAllDownloading.ItemsSource != null ? this.llsAllDownloading.ItemsSource.Count.ToString() : "0");
        }

        private void appBarSelectAll_Click(object sender, EventArgs e)
        {
            var appBarIcon = sender as ApplicationBarIconButton;
            if (appBarIcon == null)
                return;

            if ("选择全部".Equals(appBarIcon.Text))
            {
                appBarIcon.Text = "取消选择";
                appBarIcon.IconUri = new Uri("/Images/Icons/uncheckedall.png", UriKind.Relative);
                //全部
                if (this.pivotAllChapter == this.pivot.SelectedItem)
                {
                    this.llsAll.IsSelectionEnabled = true;
                }
                //
                foreach (var item in this.llsAll.ItemsSource)
                {
                    var container = this.llsAll.ContainerFromItem(item) as LongListMultiSelectorItem;
                    if (container != null) container.IsSelected = true;
                }
            }
            else
            {
                appBarIcon.Text = "选择全部";
                appBarIcon.IconUri = new Uri("/Images/Icons/checkedall.png", UriKind.Relative);
                //全部
                if (this.pivotAllChapter == this.pivot.SelectedItem)
                {
                    this.llsAll.IsSelectionEnabled = false;
                }
            }


        }

        private void appBarDelete_Click(object sender, EventArgs e)
        {
            if (this.pivotAllChapter == this.pivot.SelectedItem)
            {
                MessageToastManager.Show(string.Format("共选择了{0}进行删除操作！", this.llsAll.SelectedItems.Count));
            }
        }

        private void appBarPause_Click(object sender, EventArgs e)
        {
            if (this.pivotAllChapter == this.pivot.SelectedItem)
            {
                MessageToastManager.Show(string.Format("共选择了{0}进行暂停操作！", this.llsAll.SelectedItems.Count));
            }
        }

        private void appBarDownload_Click(object sender, EventArgs e)
        {
            if (this.pivotAllChapter == this.pivot.SelectedItem)
            {
                MessageToastManager.Show(string.Format("共选择了{0}进行下载操作！", this.llsAll.SelectedItems.Count));
            }
        }

        #region 全部选择
        private void llsAll_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.pivotAllChapter == this.pivot.SelectedItem)
            {
                if (!this.llsAll.IsSelectionEnabled)
                {
                    var appBarIcon = ApplicationBar.Buttons[0] as ApplicationBarIconButton;
                    if (appBarIcon == null)
                        return;

                    if ("取消选择".Equals(appBarIcon.Text))
                    {
                        appBarIcon.Text = "选择全部";
                        appBarIcon.IconUri = new Uri("/Images/Icons/checkedall.png", UriKind.Relative);
                    }
                }
            }
        }
        #endregion 全部选择

        /// <summary>
        /// 下载/暂停/阅读章节
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imageOperator_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Image image = sender as Image;
            if (image == null)
                return;
            if (image.Tag == null)
                return;
            string imageName = Convert.ToString(image.Tag);
            if (string.IsNullOrWhiteSpace(imageName))
                return;
            DownloadComicChapter dcc = image.DataContext as DownloadComicChapter;
            if (dcc == null)
                return;
            //缓存
            string key = string.Format(KEYS.CACHEDOWNLOAD_CHAPTER_IMAGE_QUEUE, this.downloadComic.ComicId, dcc.PartId);
            //
            if (imageName.EndsWith("download.png"))//下载
            {
                //TODO 已经存在了，遍历是否还有未下载的数据
                if (IsolatedStorageHelper.Instance.FileExists(key))
                {
                    ObservableCollection<DownloadComicChapterImage> localDownloadComicChapterImages = null;
                    string localCacheData = IsolatedStorageHelper.Instance.ReadText(key);
                    if (!string.IsNullOrWhiteSpace(localCacheData))
                    {
                        localDownloadComicChapterImages = JSONHelper.Deserialize<ObservableCollection<DownloadComicChapterImage>>(localCacheData);
                    }
                    IsInitialTransfer = true;
                    this.AddDownloadComicChapterImageToTransferQueue(localDownloadComicChapterImages, key);
                    return;
                }

                //获取漫画的章节中的图片地址，并缓存在本地
                #region 获取漫画章节中的图片地址列表
                string requestUrl = string.Concat(KEYS.REQUEST_HOST, string.Format("/comic/comicsread_v3?bookid={0}&partid={1}&partVersion=3", this.downloadComic.ComicId, dcc.PartId));
                LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
                //
                WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
                IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
                {
                    try
                    {
                        this.Dispatcher.BeginInvoke(() =>
                        {
                            #region 获取结果处理
                            string result = webTask.EndWebTask(callBackResult);

                            if (string.IsNullOrWhiteSpace(result))
                            {
                                LogHelper.LogError("Result is empty.");
                                //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                                return;
                            }
                            //
                            if (result.StartsWith("exception:"))
                            {
                                LogHelper.LogError(result);
                                return;
                            }
                            LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                            //

                            var rootCharacterString = JSONHelper.Deserialize<JsonComicContent>(result);
                            if (!(rootCharacterString != null && !string.IsNullOrWhiteSpace(rootCharacterString.Info)))
                            {
                                //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                            }
                            else
                            {
                                var comicImages = new ObservableCollection<DownloadComicChapterImage>();
                                var itemsource = JSONHelper.Deserialize<ObservableCollection<JsonComicContentInfo>>(rootCharacterString.Info);
                                if (itemsource != null && itemsource.Count > 0)
                                {
                                    foreach (JsonComicContentInfo jcci in itemsource)
                                    {
                                        comicImages.Add(new DownloadComicChapterImage()
                                        {
                                            ComicId = this.downloadComic.ComicId,
                                            PartId = dcc.PartId,
                                            ImageUrl = jcci.Imgurl,
                                            Referer = jcci.Referer,
                                            DownloadStatus = (int)DownloadComicChapterStatus.Pending
                                        });
                                    }
                                }
                                //漫画的章节中的图片地址列表
                                if (comicImages != null && comicImages.Count > 0)
                                {
                                    //缓存
                                    string text = JSONHelper.Serialize<ObservableCollection<DownloadComicChapterImage>>(comicImages);
                                    IsolatedStorageHelper.Instance.WriteText(text, key);
                                    LogHelper.LogInfo(key, this.GetType(), MethodBase.GetCurrentMethod());
                                    #region 添加至后台下载队列
                                    foreach (DownloadComicChapterImage dcci in comicImages)
                                    {
                                        if (BackgroundTransferService.Requests.Count() >= 25)
                                        {
                                            break;
                                        }
                                        Uri transferUri = new Uri(Uri.EscapeUriString(dcci.ImageUrl), UriKind.RelativeOrAbsolute);
                                        BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
                                        transferRequest.Method = "GET";
                                        Uri downloadUri = new Uri(string.Concat("shared/transfers/", KEYS.CacheImagePrefix, dcci.ComicId, "_", dcci.PartId, "_", MD5.GetMd5String(dcci.ImageUrl)), UriKind.RelativeOrAbsolute);
                                        transferRequest.DownloadLocation = downloadUri;
                                        LogHelper.LogInfo(downloadUri.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                                        //
                                        transferRequest.Tag = JSONHelper.Serialize<DownloadComicChapterImage>(dcci);
                                        transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
                                        try
                                        {
                                            BackgroundTransferService.Add(transferRequest);
                                        }
                                        catch (Exception err) { LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod()); }
                                    }
                                    #endregion 添加至后台下载队列
                                }
                                else
                                {
                                    //更新漫画的章节缓存中的下载状态
                                    UpdateLocalCacheFromDownloadComicChapter(this.downloadComic.ComicId, dcc.PartId, DownloadComicChapterStatus.ErrorEmptyImageList);
                                }
                            }
                            #endregion 获取结果处理
                        });
                    }
                    catch (Exception err)
                    {

                    }
                }, webTask);
                #endregion 获取漫画章节中的图片地址列表
                //
                BitmapImage bi = new BitmapImage(new Uri("/Images/Icons/pause.png", UriKind.Relative));
                image.Source = bi;
            }
            else if (imageName.EndsWith("pause.png"))//暂停
            {
                BitmapImage bi = new BitmapImage(new Uri("/Images/Icons/download.png", UriKind.Relative));
                image.Source = bi;
            }
            else if (imageName.EndsWith("play.png"))//阅读
            {
            }
        }





        #region ******************************下载队列数据更新******************************
        private IEnumerable<BackgroundTransferRequest> transferRequests;
        private void InitialTransferStatusCheck()
        {
            UpdateRequestsList();

            foreach (var transfer in transferRequests)
            {
                transfer.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferStatusChanged);
                transfer.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
                ProcessTransfer(transfer);
            }
        }

        /// <summary>
        /// 该方法使用 BackgroundTransferService 类的 Requests 属性检索当前已为该应用注册的传输请求列表。
        /// <para>该属性返回新 BackgroundTransferRequest 对象的列表。</para>
        /// <para>由于对象是新的，因此请确保针对任何现有对象引用调用 Dispose 以避免内存泄露。</para>
        /// </summary>
        private void UpdateRequestsList()
        {
            // The Requests property returns new references, so make sure that
            // you dispose of the old references to avoid memory leaks.
            if (transferRequests != null)
            {
                foreach (var request in transferRequests)
                {
                    request.Dispose();
                }
            }
            if (BackgroundTransferService.Requests.Count() <= 0)
            {
                
            }
            transferRequests = BackgroundTransferService.Requests;
        }

        void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {
            ProcessTransfer(e.Request);
            UpdateUI();
        }

        void transfer_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
        {
            UpdateUI();
        }

        private void ProcessTransfer(BackgroundTransferRequest transfer)
        {
            switch (transfer.TransferStatus)
            {
                case TransferStatus.Completed:

                    // If the status code of a completed transfer is 200 or 206, the
                    // transfer was successful
                    if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
                    {
                        //从队列移除
                        RemoveTransferRequest(transfer.RequestId);
                        //
                        DownloadComicChapterImage dcci = JSONHelper.Deserialize<DownloadComicChapterImage>(transfer.Tag);
                        string filefullpath = string.Empty;
                        if (dcci == null)
                        {
                            return;
                        }
                        string filename = string.Concat(KEYS.ComicIslandCacheDirectory, "/", KEYS.CacheImagePrefix, dcci.ComicId, "_", dcci.PartId, "_", MD5.GetMd5String(dcci.ImageUrl));
                        LogHelper.LogInfo(filename, this.GetType(), MethodBase.GetCurrentMethod());

                        //将下载的文件移到指定目录下
                        using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            try
                            {
                                if (!isoStore.FileExists(filename))
                                {
                                    //isoStore.DeleteFile(filename);
                                    isoStore.MoveFile(transfer.DownloadLocation.OriginalString, filename);
                                }
                            }
                            catch (Exception err)
                            {
                                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                            }
                        }
                        //更新缓存状态
                        string key = string.Format(KEYS.CACHEDOWNLOAD_CHAPTER_IMAGE_QUEUE, dcci.ComicId, dcci.PartId);
                        if (!IsolatedStorageHelper.Instance.FileExists(key))
                        {
                            return;
                        }
                        string text = IsolatedStorageHelper.Instance.ReadText(key);
                        var items = JSONHelper.Deserialize<ObservableCollection<DownloadComicChapterImage>>(text);

                        if (items != null && items.Count > 0)
                        {
                            foreach (DownloadComicChapterImage itemDcci in items)
                            {
                                if (itemDcci.ComicId == dcci.ComicId && itemDcci.PartId == dcci.PartId && itemDcci.ImageUrl.Equals (dcci.ImageUrl))
                                {
                                    itemDcci.DownloadStatus = (int)DownloadComicChapterStatus.Completed;
                                    break;
                                }
                            }
                            var newText = JSONHelper.Serialize<ObservableCollection<DownloadComicChapterImage>>(items);
                            IsolatedStorageHelper.Instance.WriteText(newText, key, true);
                        }
                        //是否下载完成
                        if (items != null && items.Count > 0)
                        {
                            bool isDownloadAll = true;
                            foreach (DownloadComicChapterImage itemDcci in items)
                            {
                                if (itemDcci == null)
                                    continue;
                                if (itemDcci.DownloadStatus == (int)DownloadComicChapterStatus.Downloading || itemDcci.DownloadStatus == (int)DownloadComicChapterStatus.Pending)
                                {
                                    isDownloadAll = false;
                                    break;
                                }
                            }
                            if (isDownloadAll)//TODO 全部下载完成，标识章节为下载完成
                            {
                                UpdateLocalCacheFromDownloadComicChapter(dcci.ComicId, dcci.PartId, DownloadComicChapterStatus.Completed);
                            }
                        }
                    }
                    else
                    {
                        //下载不正确时，从队列移除或做其它处理
                        RemoveTransferRequest(transfer.RequestId);

                        if (transfer.TransferError != null)
                        {
                            //还有队列则继续处理
                        }
                    }
                    break;
            }
        }

        private void RemoveTransferRequest(string transferID)
        {
            // Use Find to retrieve the transfer request with the specified ID.
            BackgroundTransferRequest transferToRemove = BackgroundTransferService.Find(transferID);

            // Try to remove the transfer from the background transfer service.
            try
            {
                BackgroundTransferService.Remove(transferToRemove);
            }
            catch (Exception e)
            {
                // Handle the exception.
            }
        }

        private void UpdateUI()
        {
            // Update the list of transfer requests
            UpdateRequestsList();
        }
        #endregion ******************************下载队列数据更新******************************

        /// <summary>
        /// 更新漫画中章节下载状态的缓存数据
        /// </summary>
        /// <param name="comicId"></param>
        /// <param name="partId"></param>
        /// <param name="status"></param>
        void UpdateLocalCacheFromDownloadComicChapter(int comicId, int partId, DownloadComicChapterStatus status)
        {
            ObservableCollection<DownloadComic> localCacheItems = null;
            if (IsolatedStorageHelper.Instance.FileExists(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE))
            {
                string localCacheData = IsolatedStorageHelper.Instance.ReadText(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE);
                if (!string.IsNullOrWhiteSpace(localCacheData))
                {
                    localCacheItems = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(localCacheData);
                }
            }
            if (localCacheItems != null && localCacheItems.Count > 0)
            {
                foreach (DownloadComic dc in localCacheItems)
                {
                    if (dc == null)
                        continue;
                    if (dc.ComicId != comicId)
                        continue;
                    foreach (DownloadComicChapter dcDcc in dc.Chapters)
                    {
                        if (dcDcc == null)
                            continue;
                        if (dcDcc.PartId == partId)
                        {
                            dcDcc.DownloadStatus = (int)DownloadComicChapterStatus.Completed;
                            break;
                        }
                    }
                }
            }
            IsolatedStorageHelper.Instance.WriteText(JSONHelper.Serialize<ObservableCollection<DownloadComic>>(localCacheItems), KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE, true);
        }

        /// <summary>
        /// 更新漫画下载状态的缓存数据
        /// </summary>
        /// <param name="downloadComic"></param>
        /// <param name="status"></param>
        void UpdateLocalCacheFromDownloadComic(DownloadComic downloadComic)
        {
            ObservableCollection<DownloadComic> localCacheItems = null;
            if (IsolatedStorageHelper.Instance.FileExists(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE))
            {
                string localCacheData = IsolatedStorageHelper.Instance.ReadText(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE);
                if (!string.IsNullOrWhiteSpace(localCacheData))
                {
                    localCacheItems = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(localCacheData);
                }
            }

            if (!(localCacheItems != null && localCacheItems.Count > 0))
            {
                return;
            }

            foreach (DownloadComic item in localCacheItems)
            {
                if (item.Total == item.TotalCompleted)
                {
                    item.DownloadStatus = (int)DownloadComicChapterStatus.Completed;
                }
            }

            IsolatedStorageHelper.Instance.WriteText(JSONHelper.Serialize<ObservableCollection<DownloadComic>>(localCacheItems), KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE, true);
        }
    }
}